﻿using System;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Web.Configuration;

namespace SelfMadeMillioniare.API.Helpers
{
    public class EmailHelper
    {
        private const string Pattern = @"^[A-Za-z0-9._+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$";

        public static bool IsEmailCorrect(string email)
        {
            Match match = Regex.Match(email, Pattern, RegexOptions.IgnoreCase);

            return match.Success;
        }

        /*public static bool SendRestorePasswordEmail(User user)
        {
            string from = WebConfigurationManager.AppSettings["SmtpFrom"];
            
            SmtpClient smtpClient = GetSmtpClient();


            const string subject = @"Restore password from Juice account";
            string body = String.Format("<p>Hi, {0}.</p>" +
                                        "<p>A password reset request has been recieved for your login.</p>" +
                                        "<p>Your passpord: <b>{1}</b></p>" +
                                        "<p>Thanks!</p> ", user.DisplayName, user.Password);

            MailMessage message = CreateMailMessage(from, user.Email, subject, body);

            try
            {
                smtpClient.Send(message);

                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }*/

        private static SmtpClient GetSmtpClient()
        {
            SmtpClient smtpClient = new SmtpClient
            {
                DeliveryMethod = SmtpDeliveryMethod.Network,
                EnableSsl = Boolean.Parse(WebConfigurationManager.AppSettings["SmtpEnableSSL"]),
                Host = WebConfigurationManager.AppSettings["SmtpHost"],
                Port = Int32.Parse(WebConfigurationManager.AppSettings["SmtpPort"])
            };

            string accountName = WebConfigurationManager.AppSettings["SmtpUserName"];
            string accountPassword = WebConfigurationManager.AppSettings["SmtpPassword"];

            System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(accountName, accountPassword);
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = credentials;

            return smtpClient;
        }

        private static MailMessage CreateMailMessage(string from, string to, string subject, string body) 
        {
            MailMessage message = new MailMessage
            {
                From = new MailAddress(from),
                Subject = subject,
                Body = body,
                IsBodyHtml = true,
            };

            message.To.Add(new MailAddress(to));

            return message;
        }
    }
}